﻿using Arch.EntityFrameworkCore.UnitOfWork;
using Microsoft.EntityFrameworkCore;
using WebApi.context;
using WebApi.model;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using WebApi.utils;

namespace WebApi.service
{
    public class UserService : BaseService<User>, IUserService
    {
        private readonly ToDoTaskContext _toDoTaskContext;

        private readonly RSA certificate; // 使用默认密钥


        public UserService(IUnitOfWork<ToDoTaskContext> unitOfWork, ToDoTaskContext toDoTaskContext) : base(unitOfWork)
        {
            _toDoTaskContext = toDoTaskContext;
        }

        public string? Login(User user)
        {
            IRepository<User> repository = unitOfWork.GetRepository<User>();

            User existUser = repository.GetFirstOrDefault(predicate: u =>
                u.Account == user.Account
                && u.Password == user.Password
            );

            if (existUser is not null)
            {
                return CreateToken(existUser);
            }

            return null;
        }

        public void Register(User user)
        {
            _toDoTaskContext.Users.Add(user);

            _toDoTaskContext.SaveChanges();
        }

        private string CreateToken(User user)
        {
            IDateTimeProvider provider = new UtcDateTimeProvider();

            var now = provider.GetNow().AddMinutes(55); // token will expire after 5 minutes 

            double secondsSinceEpoch = UnixEpoch.GetSecondsSince(now);


            // 创建 JWT
            var payload = new Dictionary<string, object>
            {
                { "userId", user.Id },
                { "userName", user.Name },
                { "userAccount", user.Account },
                { "exp", secondsSinceEpoch }
            };


            const string key = null; // not needed if algorithm is asymmetric


            return TokenUtils.Encoder.Encode(payload, key);
        }
    }
}